<template>
  <div class="theme-content-item" style="position: relative;">
    <div class="padding-20px form-style">
      <div class="left-title">{{ title }}</div>
      <el-form ref="teacherFormRef" label-width="120px" :model="form" :rules="rules"
        style="margin-top: 40px">
        <el-row style="display: flex;justify-content:start">
          <el-col :span="10">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="排序" prop="orderNum">
              <el-input v-model="form.orderNum" type="number" placeholder="请输入排序"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="授课范围" prop="teacherScopeIdList">
              <el-cascader ref="courseTypeRef" v-model="form.teacherScopeIdList" placeholder="请选择课程" :options="data.courseList"
                           :collapse-tags="true" :collapse-tags-tooltip="true" @change="changeCourseHandle"
                           :props="{label:'name',value:'id',children:'children',emitPath:false,multiple: true}"/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="标签" prop="tagList">
              <el-select clearable v-model="form.tagList" placeholder="请选择标签" multiple :collapse-tags="true" :collapse-tags-tooltip="true">
                <el-option v-for="item in data.teacherTagList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="学历" prop="academic">
              <el-input v-model="form.academic" placeholder="请输入学历"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="介绍" prop="introduce">
              <el-input type="textarea" v-model="form.introduce" placeholder="请输入介绍"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="是否推荐首页" prop="recommendFlag">
              <el-radio v-model="form.recommendFlag" :label="1">是</el-radio>
              <el-radio v-model="form.recommendFlag" :label="0">否</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="头像" prop="avatarPicUrl">
              <el-upload class="avatar-uploader" name="fileList" :action="$uploadUrl" :headers="headers" :show-file-list="false"
                         :on-success="handleUploadSuccess" :on-error="handleUploadError" accept=".jpeg,.png,.jpg,.bmp">
                <img style="width: 118px; height: 137px; object-fit: scale-down;" v-if="form.avatarPicUrl" :src="form.avatarPicUrl"
                     class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style=" position: fixed; bottom: 5%; left: 45%" class="flex-jc-s-b">
        <el-button size="small" @click="goBack()">
          <svg-icon icon-class="back" class="el-input__icon input-icon" />
          <span style="margin-left: 5px;">关 闭</span>
        </el-button>
        <el-button size="small" style="margin-left: 20px;" type="primary" @click="save">
          <svg-icon icon-class="save" class="el-input__icon input-icon" />
          <span style="margin-left: 5px;">保 存</span>
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { getToken } from '@/utils/auth'
import {addTeacher, editTeacher, getTeacherDetail} from '@/api/teacher'
import {listDictItemByCode} from '@/api/config/dic'
const headers = ref({ Authorization: "Bearer " + getToken() });
const { proxy } = getCurrentInstance();
const route = useRoute()
const router = useRouter()
const routeQuery = reactive(route.query)
const title = ref('');
const isAdd = ref(false);
const data = reactive({
  courseList: [],
  teacherTagList: [],
})
const form = reactive({
  id: null,
  orderNum: '',
  name: '',
  academic: '',
  avatarPicUrl: '',
  recommendFlag: 1,
  introduce: '',
  tagList: [],
  teacherScopeIdList: [],
})

const rules = ({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  orderNum: [{ required: true, message: '请输入排序', trigger: 'blur' }],
  academic: [{ required: true, message: '请输入学历', trigger: 'blur' }],
  teacherScopeIdList: [{ required: true, message: '请选择课程', trigger: 'blur' }],
  tagList: [{ required: true, message: '请选择标签', trigger: 'blur' }],
  avatarPicUrl: [{ required: true, message: '请选择头像', trigger: 'blur' }],
  recommendFlag: [{ required: true, message: '请选择', trigger: 'blur' }],
  introduce: [{ required: true, message: '请输入介绍', trigger: 'blur' }],
})
function handleUploadSuccess(response) {
  form.avatarPicUrl = response.data[0].url
  ElMessage({ message: "上传成功", type: 'success' })
}
function handleUploadError(Error) {
  ElMessage.error("上传失败")
}

// 详情
const initDetail = (row) => {
  getTeacherDetail(row.id || route.query.id).then((res) => {
    let resData = res.data
    Object.keys(form).forEach((key) => { form[`${key}`] = resData[`${key}`] })
    form.tagList = []
    form.teacherScopeIdList = []
    resData.tagMap.map(item => {
      form.tagList.push(item.id)
    })
    resData.teacherScopeMap.map(item => {
      form.teacherScopeIdList.push(item.id)
    })
  })
}
const initData = () => {
  listDictItemByCode({typeCode: 'courseTypeCode'}).then(res => {
    data.courseList = res.rows
  })
  listDictItemByCode({typeCode: 'teacherTagCode'}).then(res => {
    data.teacherTagList = res.rows
  })
}

function changeCourseHandle() {
  let courseTypeRef = proxy.$refs["courseTypeRef"]
  // let pathLabels = courseTypeRef.getCheckedNodes()[0].pathLabels
  // form.courseName = pathLabels[0] + '-' +pathLabels[1]
}

const save = () => {
  proxy.$refs["teacherFormRef"].validate(valid => {
    if (valid) {
      if (isAdd.value) {
        addTeacher(form).then(res => {
          if (res.code === 200) {
            clearForm()
            ElMessage.success('新增成功');
          }
        })
      } else {
        editTeacher(form).then(res => {
          if (res.code === 200) {
            ElMessage.success('修改成功');
          }
        })
      }
    }
  })
}
function goBack() {
  proxy.$tab.closeOpenPage();
  router.go(-1)
}
function clearForm() {
  Object.keys(form).forEach((key)=>{
    form[key] = ''
  })
  form.publishedFlag = 1
}

onMounted(() => {
  let titleMap = {
    add: '新增',
    edit: '修改',
  }
  routeQuery.type ? title.value = titleMap[routeQuery.type] : ''
  routeQuery.type == 'edit' ? initDetail(route.query) : ''
  isAdd.value = routeQuery.type == 'add'
  initData()
})
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  text-align: center;
}
</style>
